package com.chenyue.cm.exception;

import com.chenyue.cm.bean.Success;
import com.mysql.cj.jdbc.exceptions.MysqlDataTruncation;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.io.IOException;
import java.net.UnknownHostException;

/**
 * 异常处理器
 *
 * @author Libingxing
 */
@RestControllerAdvice
public class SysRuntimeExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(SysRuntimeException.class)
    public Success handleSysRuntimeException(SysRuntimeException e) {
        return Success.error(e.getCode(), e.getMsg());
    }

    @ExceptionHandler(IOException.class)
    public Success handleIoException(IOException e) {
        logger.error(e.getMessage(), e);
        return Success.error("网络访问失败");
    }

    @ExceptionHandler(UnknownHostException.class)
    public Success handleUnknownHostException(UnknownHostException e) {
        logger.error(e.getMessage(), e);
        return Success.error("系统无法链接到您当前所在的网络，请在关闭无线网络代理后重试");
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public Success handlerNoFoundException(MaxUploadSizeExceededException e) {
        logger.error(e.getMessage(), e);
        return Success.error("文件过大，无法上传");
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Success handleDuplicateKeyException(DuplicateKeyException e) {
        logger.error(e.getMessage(), e);
        return Success.error("当前记录已存在，请重新启动APP重试");
    }

    @ExceptionHandler(AuthorizationException.class)
    public Success handleAuthorizationException(AuthorizationException e) {
        logger.error(e.getMessage(), e);
        return Success.error("您没有使用改功能的权限，请联系管理员");
    }

    @ExceptionHandler(MysqlDataTruncation.class)
    public Success handleDataTruncationException(MysqlDataTruncation e) {
        logger.error(e.getMessage(), e);
        return Success.error("请输入的内容过大");
    }

    @ExceptionHandler(Exception.class)
    public Success<String> handleException(Exception e) {
        logger.error(e.getMessage(), e);
        return Success.error("系统繁忙");
    }
}
